<template>
  <div class="storage-order-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>入库单</h2>
      <el-button type="text" @click="handleBack">返回</el-button>
    </div>

    <!-- 查询与操作区域 -->
    <div class="search-action-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="请输入关键字查询" 
        class="search-input"
        clearable
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="success" @click="handleAddOrder">新增入库单</el-button>
    </div>

    <!-- 入库单表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      stripe 
      class="order-table"
      v-loading="loading"
    >
      <el-table-column prop="time" label="时间" sortable />
      <el-table-column prop="orderNo" label="入库单编号" />
      <el-table-column prop="warehouse" label="仓库" />
      <el-table-column prop="operator" label="操作人" />
      <el-table-column prop="status" label="入库状态">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewDetail(scope.row)"
          >
            明细
          </el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="handleEditOrder(scope.row)"
            v-if="scope.row.status !== '已完成'"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteOrder(scope.row.id)"
            v-if="scope.row.status !== '已完成'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <span class="total-info">共 {{ totalOrders }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalOrders"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑入库单弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEditMode ? '编辑入库单' : '新增入库单'" 
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="formData" 
        ref="formRef" 
        :rules="formRules" 
        label-width="120px"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库时间" prop="time">
              <el-date-picker 
                v-model="formData.time" 
                type="date" 
                placeholder="选择入库时间" 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单编号" prop="orderNo">
              <el-input 
                v-model="formData.orderNo" 
                placeholder="输入入库单编号" 
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="formData.warehouse" placeholder="选择仓库" clearable>
                <el-option 
                  v-for="item in warehouseOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人" prop="operator">
              <el-input v-model="formData.operator" placeholder="输入操作人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库状态" prop="status">
              <el-select v-model="formData.status" placeholder="选择入库状态">
                <el-option label="已完成" value="已完成" />
                <el-option label="进行中" value="进行中" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="入库产品明细">
          <el-table 
            :data="formData.productDetails" 
            border 
            stripe 
            class="detail-table"
          >
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="productNo" label="产品编号" />
            <el-table-column prop="quantity" label="数量">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeProduct(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button 
            type="text" 
            @click="addProduct"
            class="add-product-btn"
          >
            + 新增产品
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveOrder"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 入库单明细弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="入库单明细" 
      width="800px"
    >
      <el-descriptions column="2" border>
        <el-descriptions-item label="入库时间">{{ currentOrder.time }}</el-descriptions-item>
        <el-descriptions-item label="入库单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ currentOrder.warehouse }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentOrder.operator }}</el-descriptions-item>
        <el-descriptions-item label="入库状态">
          <el-tag 
            :type="currentOrder.status === '已完成' ? 'success' : 'info'"
          >
            {{ currentOrder.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-table-container">
        <h3 class="detail-table-title">入库产品明细</h3>
        <el-table 
          :data="currentOrder.productDetails" 
          border 
          stripe 
          class="detail-table"
        >
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="productNo" label="产品编号" />
          <el-table-column prop="quantity" label="数量" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog 
      v-model="deleteConfirmVisible" 
      title="确认删除" 
      width="300px"
    >
      <p>确定要删除此入库单吗？此操作不可撤销。</p>
      <template #footer>
        <el-button @click="deleteConfirmVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由实例
const router = useRouter()

// 状态管理
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)
const totalPages = ref(0)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const deleteConfirmVisible = ref(false)
const isEditMode = ref(false)
const currentOrder = ref({})
const deleteOrderId = ref(null)

// 表单引用（直接定义，与模板ref同名）
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  time: '',
  orderNo: '',
  warehouse: '',
  operator: '',
  status: '已完成',
  remark: '',
  productDetails: [
    { productName: '', productNo: '', quantity: 1 }
  ]
})

// 表单验证规则
const formRules = {
  time: [{ required: true, message: '请选择入库时间', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入入库单编号', trigger: 'blur' }],
  warehouse: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
  operator: [{ required: true, message: '请输入操作人', trigger: 'blur' }],
  productDetails: [{ 
    validator: (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('至少添加一个产品'))
      } else {
        callback()
      }
    }, 
    trigger: 'blur' 
  }]
}

// 仓库下拉选项
const warehouseOptions = [
  { label: '001仓库', value: '001' },
  { label: '002仓库', value: '002' },
  { label: '003仓库', value: '003' },
  { label: '004仓库', value: '004' }
]

// 入库单数据
const storageOrders = reactive([
  {
    id: 1,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00001',
    warehouse: '001',
    operator: '陈晨',
    status: '已完成',
    remark: '1号',
    productDetails: [
      { productName: '丝芙兰精华', productNo: 'SP001', quantity: 10 },
      { productName: '兰蔻粉水', productNo: 'LC002', quantity: 5 }
    ]
  },
  {
    id: 2,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00001',
    warehouse: '002',
    operator: '陈光',
    status: '已完成',
    remark: '2号',
    productDetails: [
      { productName: '雅诗兰黛小棕瓶', productNo: 'YS003', quantity: 8 },
      { productName: 'SK-II神仙水', productNo: 'SK004', quantity: 3 }
    ]
  },
  {
    id: 3,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00001',
    warehouse: '003',
    operator: '陈鹿',
    status: '已完成',
    remark: '3号',
    productDetails: [
      { productName: '资生堂红腰子', productNo: 'ZS005', quantity: 6 },
      { productName: '海蓝之谜面霜', productNo: 'HL006', quantity: 2 }
    ]
  },
  {
    id: 4,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00001',
    warehouse: '004',
    operator: '陈晨',
    status: '已完成',
    remark: '4号',
    productDetails: [
      { productName: '娇兰复原蜜', productNo: 'JL007', quantity: 7 },
      { productName: '纪梵希散粉', productNo: 'JF008', quantity: 4 }
    ]
  }
])

// 过滤后的入库单（分页+搜索）
const filteredOrders = computed(() => {
  // 搜索过滤
  let result = storageOrders.filter(order => {
    const keyword = searchKeyword.value.toLowerCase()
    return (
      order.orderNo.toLowerCase().includes(keyword) ||
      order.warehouse.toLowerCase().includes(keyword) ||
      order.operator.toLowerCase().includes(keyword) ||
      order.status.toLowerCase().includes(keyword)
    )
  })

  // 更新总数
  totalOrders.value = result.length
  totalPages.value = Math.ceil(totalOrders.value / pageSize.value)

  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  return result.slice(startIndex, startIndex + pageSize.value)
})

// 生命周期：初始化
onMounted(() => {
  // 模拟加载数据
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1 // 搜索后重置到第一页
}

// 返回事件
const handleBack = () => {
  router.back()
}

// 新增入库单
const handleAddOrder = () => {
  isEditMode.value = false
  // 重置表单
  Object.assign(formData, {
    id: null,
    time: '',
    orderNo: '',
    warehouse: '',
    operator: '',
    status: '已完成',
    remark: '',
    productDetails: [
      { productName: '', productNo: '', quantity: 1 }
    ]
  })
  dialogVisible.value = true
}

// 编辑入库单
const handleEditOrder = (row) => {
  isEditMode.value = true
  // 复制数据到表单
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 查看明细
const handleViewDetail = (row) => {
  currentOrder.value = { ...row }
  detailVisible.value = true
}

// 删除入库单（显示确认）
const handleDeleteOrder = (id) => {
  deleteOrderId.value = id
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  loading.value = true
  setTimeout(() => {
    const index = storageOrders.findIndex(order => order.id === deleteOrderId.value)
    if (index !== -1) {
      storageOrders.splice(index, 1)
    }
    deleteConfirmVisible.value = false
    loading.value = false
    ElMessage.success('入库单已删除')
  }, 500)
}

// 新增产品
const addProduct = () => {
  formData.productDetails.push({ productName: '', productNo: '', quantity: 1 })
}

// 删除产品
const removeProduct = (index) => {
  if (formData.productDetails.length > 1) {
    formData.productDetails.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个产品')
  }
}

// 保存入库单
const handleSaveOrder = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      setTimeout(() => {
        if (isEditMode.value) {
          // 编辑模式：更新现有数据
          const index = storageOrders.findIndex(order => order.id === formData.id)
          if (index !== -1) {
            storageOrders[index] = { ...formData }
          }
          ElMessage.success('入库单已更新')
        } else {
          // 新增模式：生成新数据
          const newId = Math.max(...storageOrders.map(o => o.id), 0) + 1
          const newOrder = {
            ...formData,
            id: newId,
            orderNo: `PD-${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${new Date().getDate().toString().padStart(2, '0')}-${newId.toString().padStart(4, '0')}`,
            time: new Date().toISOString().split('T')[0].replace(/-/g, '.')
          }
          storageOrders.unshift(newOrder)
          ElMessage.success('入库单已创建')
        }
        dialogVisible.value = false
        loading.value = false
      }, 500)
    }
  })
}

// 关闭弹窗
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = false
}
</script>

<style scoped>
.storage-order-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.order-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.order-form {
  margin-top: 10px;
}

.detail-table-container {
  margin-top: 20px;
}

.detail-table-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.detail-table {
  width: 100%;
}

.add-product-btn {
  margin-top: 10px;
  color: #409EFF;
}

.add-product-btn:hover {
  color: #66b1ff;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-action-bar {
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
}
</style>